package PartF;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;

public class Request implements Runnable {
	
	Socket socket;
	
	public Request (Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			processRequest();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	private void processRequest() throws Exception {
		
		byte[] buffer = new byte[1024];
		int bytes = 0;
		
		InputStream is = socket.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		
		int cn = getConnectionNumber();
		
		while ((bytes = dis.read(buffer)) != -1) {
			int mn = getMessageNumber();
			dos.writeBytes(cn + "." + mn + ": ");
		    dos.write(buffer, 0, bytes);
		}
		is.close();
		dis.close();
		dos.close();
		socket.close();	
	}
	private synchronized int getConnectionNumber() {
		EchoServer.incConnection();
		return EchoServer.getConnectionNumber();
	}
	private synchronized int getMessageNumber() {
		EchoServer.incMessage();
		return EchoServer.getMessageNumber();
	}
}
